package de.stromhaltig.grid;

import java.util.ArrayList;

import javax.swing.text.html.HTMLDocument.Iterator;

public class ACConnectMonitor implements Runnable {
	
	
	private static ACConnectMonitor instance = new ACConnectMonitor();
	private boolean oldStatus=false;
	private ArrayList<ACStatusListener> listeners= new ArrayList();
	
	
	private ACConnectMonitor() {
		this.oldStatus=onAC();	
		Thread thread = new Thread(this);
		thread.start();
	}

	
	public boolean onAC() {
		Kernel32.SYSTEM_POWER_STATUS batteryStatus = new Kernel32.SYSTEM_POWER_STATUS();
		Kernel32.INSTANCE.GetSystemPowerStatus(batteryStatus);
		
		
		if(batteryStatus.getACLineStatusString().indexOf("Online")==0) {
			return true;
		} return false;
		
	}
	public static ACConnectMonitor getInstance() {
		return instance;
	}
	
	public void addStatusListener(ACStatusListener listener) {
		this.listeners.add(listener);
	}
	
	public void run() {
		while(true) {			
			if(oldStatus!=onAC()) {
				oldStatus=onAC();	
				if(listeners.size()>0) {
					java.util.Iterator<ACStatusListener> iter = listeners.iterator();
					while(iter.hasNext()) {
						ACStatusListener listener = iter.next();
						listener.statusChangeEvent(this.oldStatus);
					}
				}
							
			}
			
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
}
